package com.lishem.carl._07tree;

import com.lishem.common.TreeNode;

import java.util.Stack;

/**
 * https://leetcode.cn/problems/sum-of-left-leaves/description/
 * <p>
 * 给定二叉树的根节点 root ，返回所有左叶子之和。
 */
public class _19LetCode404_左叶子之和 {

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        TreeNode pre = root;
        while (!stack.isEmpty()) {
            root = stack.pop();
            if (root.left == null && root.right == null && pre.left == root) {
                sum += root.val;
            }
            pre = root;
            if (root.right != null) {
                stack.push(root.right);
            }
            if (root.left != null) {
                stack.push(root.left);
            }
        }
        return sum;
    }

    public static void main(String[] args) {
        _19LetCode404_左叶子之和 sol = new _19LetCode404_左叶子之和();
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(sol.sumOfLeftLeaves(root));
    }
}
